package com.siblings.loan.ui.user.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Paint
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import com.lib.base.utils.helper.ActivityStackManager
import com.lib.base.utils.thread.TimingThread
import com.siblings.loan.R
import com.siblings.loan.databinding.ActLoginBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.tab.act.SibMainAct
import com.siblings.loan.ui.PaPoyAct
import com.siblings.loan.ui.user.impl.SibLoginPresenterImpl
import com.siblings.loan.ui.user.view.ISibLoginView
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.mvp.MvpAct
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/8 11:12
 * @Annotation：登录
 */
class SibLoginAct: MvpAct<ISibLoginView, SibLoginPresenterImpl>(),ISibLoginView,TimingThread.ITimingThreadListener {

    lateinit var binding: ActLoginBinding

    //倒计时
    private var count = 60
    private var timeThread: TimingThread? = null

    override fun createMvpPresenter(): SibLoginPresenterImpl {
        return SibLoginPresenterImpl(this)
    }

    override fun getSibRootView(): View {
        binding = ActLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initSibView() {
        setSibTitleBarVisibility(View.VISIBLE)
        setSibTitleBarColor(Color.parseColor("#FFFFFF"))
        setSibTextTitle("")
        setSibBackBtnVisibility(View.INVISIBLE)
        setSibRightBtnVisibility(View.INVISIBLE)

        //关闭所有页面
        ActivityStackManager.finishAllActivity(SibLoginAct::class.java)
        checkSibLoginBtnState()
    }

    @SuppressLint("SetTextI18n")
    override fun initSibData() {
        binding.textZoneCode.text = "+${SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_TIMEZONE_CODE)}"
        binding.textZoneCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.textZoneCode.paint.isAntiAlias = true//抗锯齿

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.app_name))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.app_name)) + getString(R.string.app_name).length
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF8378")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPrivacyPolicy.text = spString
    }

    override fun initSibListener() {
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkSibLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }
        //电话号码输入框焦点监听
        binding.editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                HttpHelper.addSibEventAction(SibEventType.FORM.SIB_FORM_LOGIN_MOBILE, getSibMobile())
            }
        }

        //验证码入框监听
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkSibLoginBtnState()
            }
        })
        binding.editCode.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editCode.clearFocus()
                true
            }
            false
        }
        //验证码输入框焦点监听
        binding.editCode.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                HttpHelper.addSibEventAction(SibEventType.FORM.SIB_FORM_LOGIN_VARIFY_CODE, getSibCode())
            }
        }

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkSibLoginBtnState()
            when (isChecked) {
                true -> {
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOGIN_PRIVACY_AGREE, "")
                }
                false -> {
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //发送验证码
        binding.btnSend.setOnClickListener {
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOGIN_NEXT, "")
            binding.editMobile.clearFocus()

            showSibLoading()
            //发送验证码
            mvpPresenter.sendSibSmsCodeAction()
        }

        //登录
        binding.btnLogin.setOnClickListener {
            onHideSoftInput(binding.editCode)
            showSibLoading()
            mvpPresenter.loginSibAction(getSibMobile(),getSibCode(),"NO")
        }

        //协议
        binding.textPrivacyPolicy.setOnClickListener {
            onIntent(PaPoyAct::class.java)
        }
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkSibLoginBtnState() {
        binding.mobileLayout.setBackgroundResource(R.drawable.sib_radius_frame_ffeceff3_12)
        binding.editMobile.setTextColor(Color.parseColor("#000000"))
        binding.wrongLayout.visibility = View.INVISIBLE
        if (binding.checkBox.isChecked && getSibMobile().isNotEmpty() && getSibCode().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
            binding.btnLogin.alpha = 1.0f
        } else {
            binding.btnLogin.isEnabled = false
            binding.btnLogin.alpha = 0.3f
        }
        checkSibSendBtnStat()
    }

    /**
     * 设置发送验证码按钮状态
     */
    private fun checkSibSendBtnStat(){
        if (getSibMobile().isNotEmpty() && count == 60){
            binding.btnSend.isEnabled = true
            binding.btnSend.alpha = 1.0f
        } else {
            binding.btnSend.isEnabled = false
            binding.btnSend.alpha = 0.3f
        }
    }

    override fun getSibMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    override fun getSibCode(): String {
        return binding.editCode.text.toString().trim()
    }

    override fun showSenCodeSuccess() {
        startTimeThread()
    }

    override fun showSibLoginFailure(data: JSONObject) {
        binding.mobileLayout.setBackgroundResource(R.drawable.sib_login_wrong_mobile)
        binding.editMobile.setTextColor(Color.parseColor("#FFF55555"))
        binding.wrongLayout.visibility = View.VISIBLE
    }

    override fun showSibMainPage() {
        //停止倒计时
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        onIntent(SibMainAct::class.java)
        finish()
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        count = 60
        checkSibSendBtnStat()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    @SuppressLint("SetTextI18n")
    override fun onLoading() {
        if (count <= 1) {
            count = 60
            checkSibSendBtnStat()
            timeThread!!.stopThread()
            binding.btnSend.text = getString(R.string.login_resend)
            return
        }
        count--
        binding.btnSend.text = "${count}S"
        checkSibSendBtnStat()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOGIN_END, "")
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
    }
}